<template>
  <VTable ref="tableRef" v-bind="tableOptins">
    <template #form="{ form }">
      <XForm :fieldList="fieldList" :formOption="optionsData" :formData="form">
        <template #create_user="{ value, input }">
          <VCascader
            :model-value="value"
            @update:model-value="input"
            collapse-tags
            class="w-[200px]"
            placeholder="创建人"
          />
        </template>
      </XForm>
    </template>
    <template #toolbar_btns>
      <VActionBar :actions="actions" />
    </template>
    <template #operation="{ row }">
      <el-button
        link
        type="primary"
        @click="handleEdit(row.id)"
        v-hasPermi="[logisticsSettingsAuthList.country.edit]"
      >
        编辑
      </el-button>
      <el-button
        link
        type="primary"
        @click="handleLog(row.id)"
        v-hasPermi="[logisticsSettingsAuthList.country.log]"
      >
        日志
      </el-button>
    </template>
  </VTable>
  <add
    type="postCode"
    v-model="visibleAdd"
    :id="idAdd"
    :optionsData="optionsData"
    @close="idAdd = ''"
    @refresh="refresh"
  />
  <Log
    dialog
    v-model="logVisible"
    :autoLoad="false"
    tag="base.zip_code"
    :business_id="logId"
    @close="logId = ''"
  />
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  <import-dialog ref="importDialogRef" @refresh="refresh" />
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import XForm from "@/components/XForm/index.vue";
import { zipCodeList, deleteZipCode } from "../../api/index.js";
import add from "../../add/index";
import Log from "@/components/Log/index.vue";
import DerivedCenter from "@/components/DerivedCenter";
import { config_name } from "@/config/export.js";
import importDialog from "@/components/importDialog/index.vue";
import { getTableSelectRow, getTableSelect } from "@/hooks/tool.js";
import { logisticsSettingsAuthList } from "@/Auth/logistics-settings.js";
const router = useRouter();
const { proxy } = getCurrentInstance();
const props = defineProps({
  optionsData: { type: Object, default: () => {} },
});
const { optionsData } = toRefs(props);
const tableRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {
      dateRange: { type: "create_time", value: [], range: false }, // 组合+日期范围
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    { fixed: "left", width: 50, title: "编号", type: "seq" },
    {
      fixed: "left",
      title: "区域名称",
      width: 120,
      field: "region_name",
    },
    { title: "区域国家", width: 200, field: "country_name" },
    { title: "匹配类型", width: 100, field: "match_type" },
    {
      title: "按分段邮编",
      minWidth: 200,
      field: "sub_code",
      slots: {
        default: ({ row }) => {
          return <div>{row?.sub_code?.join(",")||'-'}</div>;
        },
      },
    },
    {
      title: "按精确邮编",
      minWidth: 200,
      field: "precise_code",
      slots: {
        default: ({ row }) => {
          return <div>{row?.precise_code?.join(",")||'-'}</div>;
        },
      },
    },
    {
      title: "按前缀邮编",
      minWidth: 200,
      field: "prefix_code",
      slots: {
        default: ({ row }) => {
          return <div>{row?.prefix_code?.join(",")||'-'}</div>;
        },
      },
    },
    {
      title: "是否FAB仓点",
      width: 110,
      field: "is_fba_warehouse",
      slots: {
        default: ({ row }) => (
          <div>{row?.is_fba_warehouse == 1 ? "是" : "否"}</div>
        ),
      },
    },
    { title: "备注", minWidth: 200, field: "remark" },
    {
      title: "创建信息",
      width: 220,
      field: "create_time",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>
                <span style="color: var(--base-sub-text-color)">创建人:</span>
                {row?.create_user || "-"}
              </div>
              <div>
                <span style="color: var(--base-sub-text-color)">创建时间:</span>
                {row?.create_time || "-"}
              </div>
            </div>
          );
        },
      },
    },
    {
      title: "更新信息",
      width: 220,
      field: "update_time",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>
                <span style="color: var(--base-sub-text-color)">更新人:</span>
                {row?.update_user || "-"}
              </div>
              <div>
                <span style="color: var(--base-sub-text-color)">更新时间:</span>
                {row?.update_time || "-"}
              </div>
            </div>
          );
        },
      },
    },
    {
      title: "操作",
      width: 110,
      fixed: "right",
      slots: { default: "operation" },
    },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        return zipCodeList({ ...form, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});

//日志
const logId = ref("");
const logVisible = ref(false);
const handleLog = (id) => {
  logId.value = id;
  logVisible.value = true;
};

//新增编辑
const idAdd = ref();
const visibleAdd = ref(false);
const handleEdit = (_id) => {
  idAdd.value = _id;
  visibleAdd.value = true;
};
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};

//删除
const handleDelete = () => {
  const id = getTableSelect(tableRef.value);
  if (!id.length) return ElMessage.warning("请至少选择一条数据!");
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认删除选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          await deleteZipCode({ id });
          ElMessage.success("操作成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};

//导入
const importDialogRef = ref();
const handleImport = () => {
  importDialogRef.value?.open({
    type: "zipCode",
    urlType: "/base/zip-code/import",
  });
};
//导出中心
const DerivedCenterRef = ref();
const handleExport = () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value?.open({
    tag_name: config_name["logistics_settings"]["zip_code_manage"],
    condition,
  });
};
const actions = [
  {
    label: "新增",
    icon: "add2",
    type: "primary",
    fn: () => (visibleAdd.value = true),
    permission: [logisticsSettingsAuthList.country.add],
  },
  {
    label: "删除",
    icon: "del",
    fn: handleDelete,
    permission: [logisticsSettingsAuthList.country.delete],
  },
  {
    label: "导入",
    right: true,
    dkicon: "icon-Download",
    fn: handleImport,
  },
  {
    label: "导出",
    right: true,
    dkicon: "icon-Upload",
    fn: handleExport,
    permission: [logisticsSettingsAuthList.country.export],
  },
];

const publicStyle = { style: { width: "240px" } };
const fieldList = [
  {
    field: "region_name",
    // originOption: "zipRegion",
    type: "input",
    placeholder: "区域名称",
    // multiple: true,
    // options: {
    //   placeholder: "区域名称",
    //   valueKey: "id",
    //   labelKey: "region_name",
    // },
    // class: "select-wrapper-style",
    style: { width: "240px" },
  },
  {
    field: "status",
    placeholder: "状态",
    type: "select",
    options: {
      placeholder: "状态",
      data: [
        { label: "启用", value: 1 },
        { label: "禁用", value: 0 },
      ],
    },
    style: { width: "90px" },
  },
  {
    field: "time",
    type: "dateTimeRange",
    style: { width: "360px" },
    selectStyle: { width: "125px" },
    select: [
      { label: "创建时间", value: "create_time" },
      { label: "最后更新时间", value: "update_time" },
    ],
    itemProps: {
      startPlaceholder: "创建最早时间",
      endPlaceholder: "创建最晚时间",
    },
  },
  {
    field: "user",
    selectStyle: { width: "85px" },
    select: [
      { label: "创建人", value: "create_user" },
      { label: "最后更新人", value: "update_user" },
    ],
    slot: "create_user",
  },
  {
    field: "country",
    type: "select",
    multiple: true,
    options: {
      placeholder: "国家",
    },
    class: "select-wrapper-style",
    style: { width: "240px" },
  },
  {
    field: "match_type",
    type: "select",
    originOption: "zip_code_match",
    options: {
      placeholder: "匹配类型",
    },
    style: { width: "120px" },
  },
  {
    field: "is_fba_warehouse",
    placeholder: "是否FAB仓点",
    type: "select",
    options: {
      placeholder: "是否FAB仓点",
      data: [
        { label: "是", value: 1 },
        { label: "否", value: 0 },
      ],
    },
    style: { width: "130px" },
  },
];
</script>
<style lang="scss" scoped>
.vx-table {
  height: calc(100% - 40px) !important;
}
</style>
